package com.windchime.blog.controller.admin;


import com.github.pagehelper.PageInfo;
import com.windchime.blog.entity.Friend;
import com.windchime.blog.entity.vo.FriendSearch;
import com.windchime.blog.result.R;
import com.windchime.blog.service.FriendService;
import com.windchime.blog.utils.StringSplitUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 友链表 前端控制器
 * </p>
 *
 * @author WindChime
 * @since 2021-08-02
 */
@RestController
@RequestMapping("/admin/friend")
public class AdminFriendController {

    @Autowired
    private FriendService friendService;

    /**
     * 分页查询带条件
     * @param page 当前页
     * @param limit 当前页条目数
     * @param friendSearch 条件
     * @return friends
     */
    @GetMapping("/selectFriendList")
    public R selectFriendList(Integer page, Integer limit, FriendSearch friendSearch) {
        PageInfo<Friend> friends = friendService.selectFriendList(page, limit, friendSearch);
        return R.ok().code(0).msg("").count(friends.getTotal()).data("friends", friends.getList());
    }

    /**
     * 保存友链
     * @param friend 友链
     * @return true
     */
    @PostMapping("/saveFriend")
    public R saveFriend(Friend friend) {
        boolean b = friendService.saveFriend(friend);
        if (b) {
            return R.ok().msg("添加成功");
        } else {
            return R.error().msg("已有该友链,请重新输入友链名");
        }
    }

    /**
     * 修改友链
     * @param friend 友链
     * @return true
     */
    @PostMapping("/editFriend")
    public R editFriend(Friend friend) {
        boolean b = friendService.editFriend(friend);
        if (b) {
            return R.ok().msg("修改成功");
        } else {
            return R.error().msg("友链名已被使用,请重新修改");
        }
    }

    /**
     * 删除友链
     * @param id 友链ID
     * @return true
     */
    @GetMapping("/deleteFriend/{id}")
    public R deleteFriend(@PathVariable Long id) {
        boolean b = friendService.removeById(id);
        if (b) {
            return R.ok().msg("删除成功");
        } else {
            return R.error().msg("删除失败");
        }
    }

    /**
     * 批量删除
     * @param ids ids数组字符串
     * @return true
     */
    @GetMapping("/deleteFriends/{ids}")
    public R deleteFriend(@PathVariable String ids) {
        List<Long> idList = StringSplitUtil.split(ids, ",");
        boolean b = friendService.removeByIds(idList);
        if (b) {
            return R.ok().msg("批量删除成功");
        } else {
            return R.error().msg("批量删除失败");
        }
    }

}

